package com.disgruntledbots;

import java.util.ArrayList;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;

public class DestructiveCollisionContactListener implements ContactListener {

	ArrayList<PhysicsEntityConnector> mObjects;
	public DestructiveCollisionContactListener(ArrayList<PhysicsEntityConnector> objects)
	{
		this.mObjects = objects;
	}
	
	@Override
	public void beginContact(Contact contact) {
		DamageablePhysicsEntity bodyA;
		DamageablePhysicsEntity bodyB;
		
		if(contact.isTouching()){
			if(contact.getFixtureA().getBody().getLinearVelocity().len() > 0.25f || contact.getFixtureA().getBody().getLinearVelocity().len() > 0.25f)
			{
				bodyA = this.findConnector(contact.getFixtureA().getBody());
				bodyB = this.findConnector(contact.getFixtureB().getBody());

				if(bodyA != null)
				{
					bodyA.recieveDamage(contact.getFixtureB().getBody());
				}

				if(bodyB != null)
				{
					bodyB.recieveDamage(contact.getFixtureA().getBody());
				}
			}
		}
	}

	@Override
	public void endContact(Contact contact) {
		// TODO Auto-generated method stub

	}

	@Override
	public void preSolve(Contact contact, Manifold oldManifold) {
		// TODO Auto-generated method stub

	}

	@Override
	public void postSolve(Contact contact, ContactImpulse impulse) {
		// TODO Auto-generated method stub

	}

	private DamageablePhysicsEntity findConnector(Body b)
	{
		for(PhysicsEntityConnector p : mObjects)
		{
			if(p != null)
			{
				if(p.mBody == b)
				{
					if(p.getClass() == DamageablePhysicsEntity.class )
					{
						return (DamageablePhysicsEntity) p;
					}
				}
			}
		}
		
		return null;
	}
}
